<?php
class System_AuthController extends Apps_Controller_Action {

	public function indexAction() {
	    $this->disallowBacktrack();
		$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('/system/auth/login');
		}
		$this->view->data = $data;
	}

	public function loginAction() {
	    $this->disallowBacktrack();
		$layout = $this->_helper->layout();
		$layout->setLayout('layout-login');

		$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if($data){
			$this->_redirect('/system/auth/index');
		}

		$users = new M_DbTable_User();
		$form = new F_Login();

		if($this->getRequest()->isPost()){
			if($form->isValid($_POST)){
				$data = $form->getValues();
				$data['password'] = md5($data['password']);

				$auth = Zend_Auth::getInstance();
				$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),'user');
				$authAdapter->setIdentityColumn('username')
							->setCredentialColumn('password');
				$authAdapter->setIdentity($data['username'])
							->setCredential($data['password']);
				$result = $auth->authenticate($authAdapter);
				if($result->isValid()){
					$storage = new Zend_Auth_Storage_Session();
					$storage->write($authAdapter->getResultRowObject());
					$this->goBack();
				} else {
					$form->getElement('username')->addError('Login failed.');
				}
			}
		}

		$this->view->form = $form;
	}

	public function changePasswordAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');
        $form = new F_Management_UserChangePassword();
        $tbUser = new M_DbTable_User();
        $r = $tbUser->fetchRow(array('id=?' => $id));

		if(!$r) {
            $this->_flashMessenger->addMessage(self::$msgNoRecordFound);
            return $this->goToActionIndex();
        }

        if($rq->isPost()) {
            if($form->isValid($rq->getParams())) {
            	$d = $form->getValues();
            	if($r['password'] != md5($d['password'])) {
            		$form->getElement('password')->addError('old password is incorect.');
            	} else {
	            	$newPassword = md5($d['newPassword']);
	            	$r = $tbUser->safelyUpdate(array('password' => $newPassword), array('id = ?' => $id));
	                $this->_flashMessenger->addMessage(
	                    $r
	                    ? self::$msgUpdateSuccess
	                    : self::$msgUpdateFailed);
	                return $this->goToActionIndex();
            	}
            }
        } else {
        }
        $this->view->form = $form;

	}

	public function logoutAction() {
		$this->disallowBacktrack();
		$storage = new Zend_Auth_Storage_Session();
		$storage->clear();
		$this->_redirect('/system/auth/login');
	}

	public function denyAction() {

	}
}